package cmd

import (
	"context"
	"database/sql"
	"fmt"
	_ "github.com/go-sql-driver/mysql" // mysql
	"strtv.cn/ad-service/bootstrap/config"
  "strtv.cn/ad-service/pkg/logger"
  "strtv.cn/ad-service/pkg/protocol/grpc"
  "strtv.cn/ad-service/pkg/protocol/rest"
  "strtv.cn/ad-service/pkg/service/v1"
)

// RunServer runs gRPC server and HTTP gateway
func RunServer() error {
	ctx := context.Background()

	if len(config.String("SERVICE.GRPCPORT")) == 0 {
		return fmt.Errorf("invalid TCP port for gRPC server: '%s'", config.String("SERVICE.GRPCPORT"))
	}

  if len(config.String("SERVICE.HTTPPORT")) == 0 {
		return fmt.Errorf("invalid TCP port for http server: '%s'", config.String("SERVICE.HTTPPORT"))
	}

	// initialize logger
	if err := logger.Init(config.Int("LOG.LEVEL"),config.String("LOG.TIMEFORMAT")); err != nil {
		return fmt.Errorf("failed to initialize logger: %v", err)
	}

	// add MySQL driver specific parameter to parse date/time
	// Drop it for another database
	param := "parseTime=true"

	dsn := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?%s",
		config.String("DB.USERNAME"),
		config.String("DB.PASSWORD"),
		config.String("DB.HOST"),
		config.String("DB.PORT"),
		config.String("DB.DATABASE"),
		param)
	db, err := sql.Open("mysql", dsn)
	if err != nil {
		return fmt.Errorf("failed to open database: %v", err)
	}
	defer db.Close()

	v1API := v1.NewDepartmentServiceServer(db)

	// run HTTP gateway
	go func() {
		_ = rest.RunServer(ctx, config.String("SERVICE.ADDR"), config.String("SERVICE.GRPCPORT"), config.String("SERVICE.HTTPPORT"))
	}()

	return grpc.RunServer(ctx, v1API, config.String("SERVICE.ADDR"), config.String("SERVICE.GRPCPORT"))
}
